SHELL_DIR=$(cd $(dirname $0); pwd)
IMAGE_NAME=mysql:5.7
CONTAINER_NAME=mysql_baimao

if [ -d "${SHELL_DIR}/mysql" ];then
    echo "⭐️ mysql文件夹已存在, 为保证安全本脚本不支持覆盖安装!"
    exit
fi

if [[ "$(docker images -q ${IMAGE_NAME})" == "" ]];then
    echo "⭐️ 本地不存在 ${IMAGE_NAME} 开始拉取...."
    docker pull registry.cn-shanghai.aliyuncs.com/baimao/${IMAGE_NAME}
    docker tag registry.cn-shanghai.aliyuncs.com/baimao/${IMAGE_NAME} ${IMAGE_NAME}
    docker rmi registry.cn-shanghai.aliyuncs.com/baimao/${IMAGE_NAME}
fi

echo "⭐️ 移除旧容器"
docker rm -f ${CONTAINER_NAME}
echo "⭐️ 启动预备容器 ${IMAGE_NAME}"
docker run -idt --name ${CONTAINER_NAME} -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 ${IMAGE_NAME}
echo "⭐️ 容器启动成功, 开始拷贝conf和log"
mkdir ${SHELL_DIR}/mysql
docker cp ${CONTAINER_NAME}:/etc/mysql ${SHELL_DIR}/mysql/conf
docker cp ${CONTAINER_NAME}:/var/log/mysql ${SHELL_DIR}/mysql/log
echo "⭐️ 移除预备容器"
docker rm -f ${CONTAINER_NAME}
echo "⭐️ 构建docker-compose.yml"
cat << EOF > ${SHELL_DIR}/docker-compose.yml
version: '3'
services:
  mysql:
    image: ${IMAGE_NAME}
    container_name: ${CONTAINER_NAME}
    command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=123456
      - TZ=Asia/Shanghai
    ports:
      - 3306:3306
    volumes:
      - ./mysql/data:/var/lib/mysql
      - ./mysql/log:/var/log/mysql
      - ./mysql/conf:/etc/mysql
    networks:
      - bridge

networks:
  bridge:
    driver: bridge
EOF
echo "⭐️ 启动全新数据库"
docker-compose -f ${SHELL_DIR}/docker-compose.yml up -d
echo "⭐️ 启动成功"